越了解WordPress發現,WordPress的生態真的太厲害了,需要的功能基本搜索一下就會有現成的了。
最近小編在寫WordPress主題嘛,想著以前寫文章總是要手動給標簽添加鏈接就很麻煩,百度一番就給出了答案,自動給文章中出現的標簽Tag增加鏈接,這不就方便多了嘛。
將下面的代碼添加到主題的 functions.php 即可:
/**
* WordPress 自動為文章標簽添加該標簽的鏈接
* https://www.wpdaxue.com/auto-add-tag-link.html
*/
function wpkj_auto_add_tag_link($content){
$limit = 1; // 設置同一個標簽添加幾次鏈接
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
$cleankeyword = stripslashes($keyword);
$url = '<a target="_blank" href="'.$link.'" title="'.str_replace('%s', addcslashes($cleankeyword, '$'), __('View all posts in %s')).'">'.addcslashes($cleankeyword, '$').'</a>';
$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s';
$content = preg_replace($regEx,$url,$content,$limit);
}
}
return $content;
}
add_filter( 'the_content', 'wpkj_auto_add_tag_link', 1 );
看到這個代碼之后,小編還想到了擴展這個功能的想法,就是在主題設置中給出讓用戶自己選擇是否開啟此功能、一篇文章出現多少個標簽鏈接,同一個標簽添加多少次鏈接的功能。這個方法后續會整理出教程來